from subprocess import call
from core.models import Menu, Action
from django.db.models import get_models
from academia.settings import PROJECT_DIR
from django.core.management.base import CommandError
from django.contrib.auth import models as auth_app
from django.db.transaction import commit
from django.utils.six.moves import input

FIXTURES = ["topics", "menus", "states", "cities"]
fixtures_loaded = False


def get_permission_codename(action, opts):
    """
    Returns the codename of the permission for the specified action.
    """
    return '%s_%s' % (action, opts.module_name)


def _get_all_permissions(opts, ctype):
    """
    Returns (codename, name) for all permissions in the given opts.
    """
    builtin = _get_builtin_permissions(opts)
    custom = list(opts.permissions)
    _check_permission_clashing(custom, builtin, ctype)
    return builtin + custom


def _check_permission_clashing(custom, builtin, ctype):
    """
    Check that permissions for a model do not clash. Raises CommandError if
    there are duplicate permissions.
    """
    pool = set()
    builtin_codenames = set(p[0] for p in builtin)
    for codename, _name in custom:
        if codename in pool:
            raise CommandError(
                "The permission codename '%s' is duplicated for model '%s.%s'." %
                (codename, ctype.app_label, ctype.model_class().__name__))
        elif codename in builtin_codenames:
            raise CommandError(
                "The permission codename '%s' clashes with a builtin permission "
                "for model '%s.%s'." %
                (codename, ctype.app_label, ctype.model_class().__name__))
        pool.add(codename)


def _get_builtin_permissions(opts):
    """
    Returns (codename, name) for all autogenerated permissions.
    By default, this is ('add', 'change', 'delete')
    """
    default_permissions = ['add', 'change', 'delete', 'list']

    perms = []
    for action in default_permissions:
        perms.append((get_permission_codename(action, opts),
            'Can %s %s' % (action, opts.verbose_name_raw)))
    return perms


def load_fixtures(fixtures):
    for fixture in fixtures:
        call(PROJECT_DIR.parent.expand() + "/manage.py loaddata " + fixture, shell=True)
    commit()


def create_permissions(app, db, menus, **kwargs):
    if not fixtures_loaded and kwargs.get('interactive', True):
        msg = ("\nWould you like to load the fixtures now? (yes/no): ")
        confirm = input(msg)
        while 1:
            if confirm not in ('yes', 'no'):
                confirm = input('Please enter either "yes" or "no": ')
                continue
            if confirm == 'yes':
                load_fixtures(FIXTURES)
            break

    from django.contrib.contenttypes.models import ContentType

    app_models = get_models(app)

    # This will hold the permissions we're looking for as
    # (content_type, (codename, name))
    searched_perms = list()
    # The codenames and ctypes that should exist.
    ctypes = set()
    for klass in app_models:
        # Force looking up the content types in the current database
        # before creating foreign keys to them.
        ctype = ContentType.objects.db_manager(db).get_for_model(klass)
        ctypes.add(ctype)
        for perm in _get_all_permissions(klass._meta, ctype):
            searched_perms.append((ctype, perm))

    # Find all the Permissions that have a content_type for a model we're
    # looking for.  We don't need to check for codenames since we already have
    # a list of the ones we're going to create.
    all_perms = set(auth_app.Permission.objects.using(db).filter(
        content_type__in=ctypes,
    ).values_list(
        "content_type", "codename"
    ))

    perms_to_create = [
        auth_app.Permission(codename=codename, name=name, content_type=ctype)
        for ctype, (codename, name) in searched_perms
        if (ctype.pk, codename) not in all_perms
    ]

    for perm in perms_to_create:
        perm.save()

    all_permissions = auth_app.Permission.objects.using(db).filter(content_type__in=ctypes)

    for perm in all_permissions:
        content_type = perm.content_type.name
        if content_type in menus:
            action = Action.objects.using(db).filter(permission__codename=perm.codename)
            if not action:
                menu = Menu.objects.get(pk=menus.get(content_type))
                Action(menu=menu, permission=perm).save()